package net.qqxh.shiro.shiroDemo;
import net.qqxh.shiro.bootStrap.AbstractShiroService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by jason on 2019/2/2 11:41
 */
@Controller
public class MainController {

    @Autowired
    AbstractShiroService shiroService;
    @GetMapping("/login")
    public String login() {
        if (SecurityUtils.getSubject().isAuthenticated()||SecurityUtils.getSubject().isRemembered()) {
            return "redirect:/";
        }
        return "login";
    }
    /**
     * POST 登录 shiro 写法
     *
     * @param username 用户名
     * @param password 密码
     * @return {Object}
     */
    @PostMapping("/login")
    public Object loginPost(HttpServletRequest request, HttpServletResponse response,
                            String username, String password, String captcha,
                            @RequestParam(value = "rememberMe", defaultValue = "0") Integer rememberMe) {
        // 改为全部抛出异常，避免ajax csrf token被刷新

        Subject user = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try{
            token.setRememberMe(true);
            user.login(token);
        }catch (IncorrectCredentialsException e){
            /*密码错误重新登录*/
            return "redirect:/login";
        }

        SavedRequest savedRequest=WebUtils.getSavedRequest(request);
        String url =savedRequest==null?"/login":savedRequest.getRequestUrl();
        return "redirect:" + url;
    }
    @GetMapping("/")
    public String index() {
        if (SecurityUtils.getSubject().isAuthenticated()||SecurityUtils.getSubject().isRemembered()) {
            return "index";
        }
        return "redirect:/login";
    }
    @GetMapping("/403")
    public String go403() {
        return "/403";
    }


    @ResponseBody
    @RequestMapping("/updatePermission")
    public Object updatePermission(){
        shiroService.updatePermission();
        return "success";
    }
}
